package com.yyf.springboot2.common;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class WebUtil {
	public static void setSession(String key, Object value) {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
		request.getSession().setAttribute(key, value);
	}
	public static Object getSession(String key) {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
		return request.getSession().getAttribute(key);
	}
	public static void setRequest(String key, Object value) {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
		request.setAttribute(key, value);
	}
	public static void removeSession(String key) {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
		request.getSession().removeAttribute(key);
	}
	public static String getContetPath(){
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
		return request.getContextPath();
	}
	public static String getRealPath(String dir){
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
		return request.getServletContext().getRealPath(dir);
	}
	public static String getUrlPath(){
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
		StringBuffer url = request.getRequestURL();
		System.out.println(url+"url");
		System.out.println(request.getRequestURI()+"uri");
		System.out.println(request.getServletContext().getContextPath() +"request.getServletContext().getContextPath()");
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).toString(); 
	}

	public static String isAdminSearchName(String searchName) {
		if(!(searchName.equals("username") || searchName.equals("name") 
				|| searchName.equals("talk") || searchName.equals("phone") 
				|| searchName.equals("idCard") || searchName.equals("email") 
				|| searchName.equals("address")
				|| searchName.equals("zType")
				|| searchName.equals("zTypex")
				)){
			return "username";
		}
		return searchName;
	}

	public static String urlDecode(String searchValue) {
		try {
			searchValue = URLDecoder.decode(searchValue, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
		return searchValue;
	}

	public static String coding(String searchValue) {
		try {
			if(searchValue!=null&&!searchValue.equals("")){
				searchValue = new String(searchValue.getBytes("ISO-8859-1"), "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			searchValue = "";
		}
		return searchValue;
	}

	public static String randomLetter(Integer count){
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String str = "";
		for (int i = 0; i < count; i++) {
			str += chars.charAt((int)(Math.random() * 62));
		}
		return str;
	}
	public static Date parseDate(String t){
		if(t == null){
			return null;
		}
		Date time = null;
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			time = format.parse(t);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return time;
	}
	public static Date parseDateHHMMSS(String date){
		if(date == null){
			return null;
		}
		Date time = null;
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			time = format.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return time;
	}
	public static String formatDouble(String format,Double d){
		DecimalFormat f = new DecimalFormat(format);
		return f.format(d);
	}
	public static String urlEncode(String str, String encoding) {
		try {
			return URLEncoder.encode(str, encoding);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static String urlDecode(String str, String encoding) {
		try {
			return URLDecoder.decode(str, encoding);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void createFile(String realPath) {
		File file = new File(realPath);
		if(file.exists()){
			if(file.exists()){
				file.delete();
			}
		}
		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static Map<String, String> getTime(Integer lastMonth){
		Map<String, String> date = new HashMap<String, String>();
		Calendar cal = Calendar.getInstance();
		cal.add(cal.MONTH, -lastMonth);
		System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
		cal.set(Calendar.DAY_OF_MONTH, 1);
		date.put("startTime", new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())+" 00:00:00");
		cal.add(Calendar.MONTH, 1);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.add(Calendar.DATE, -1);
		date.put("month",new SimpleDateFormat("yyyy-MM").format(cal.getTime()));
		date.put("endTime", new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())+" 59:59:59");
		return date;
	}
	public static String formatDateYYYYMMDD(Date time) {
		if(time != null){
			return new SimpleDateFormat("yyyy-MM-dd").format(time);
		}
		return null;
	}
	public static Date monthFirst(){
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_MONTH, 1);
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return format2.parse(format.format(c.getTime())+" 00:00:00");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return new Date();
	}
	public static Date monthLast(){
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 1);
		c.set(Calendar.DAY_OF_MONTH, 0);
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return format2.parse(format.format(c.getTime())+" 59:59:59");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return new Date();
	}

	public static String getIpAddr() {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}


	/**
	 * 获取项目根路径
	 *
	 */
	public static   String webUri(){
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
		String webUri = request.getServletPath();
		return webUri;
	}




}
